package org.adorsys.aderp.aderplogin.client.oauth;

import org.adorsys.aderp.aderplogin.client.common.TokenProvider;
import org.springframework.security.oauth2.client.context.OAuth2ClientContext;
import org.springframework.security.oauth2.client.context.OAuth2ClientContextHolder;
import org.springframework.security.oauth2.client.http.AccessTokenRequiredException;
import org.springframework.security.oauth2.client.resource.OAuth2ProtectedResourceDetails;
import org.springframework.security.oauth2.common.OAuth2AccessToken;

public class OauthClientTokenProvider implements TokenProvider {

	private OAuth2ProtectedResourceDetails oauthResource;

	public OAuth2AccessToken getOAuth2AccessToken() {
		OAuth2ClientContext context = OAuth2ClientContextHolder.getContext();
		if (context == null) {
			throw new IllegalStateException(
					"An OAuth2 security context hasn't been established. Unable to load the access tokens for the following resources: "
							);
		}
		OAuth2AccessToken accessToken = context.getAccessToken(oauthResource);
		if (accessToken == null) {
			throw new AccessTokenRequiredException("Access token for resource '" + oauthResource.getId()
					+ "' has not been obtained.", oauthResource);
		}
		return accessToken;
	}

	@Override
	public String getToken() {
		return getOAuth2AccessToken().getValue();
	}

	public void setOauthResource(OAuth2ProtectedResourceDetails oauthResource) {
		this.oauthResource = oauthResource;
	}
	
	
}
